import { createStore } from 'vuex'
import { currentAuthAPI } from '@/services/api'

export default createStore({
  state: {
    // 用户认证状态
    user: null,
    token: localStorage.getItem('authToken') || null,
    isAuthenticated: !!localStorage.getItem('authToken'),
    loading: false,
    error: null
  },
  getters: {
    // 获取当前用户
    currentUser: (state) => state.user,
    // 是否已登录
    isLoggedIn: (state) => state.isAuthenticated,
    // 获取用户token
    userToken: (state) => state.token,
    // 获取加载状态
    isLoading: (state) => state.loading,
    // 获取错误信息
    authError: (state) => state.error
  },
  mutations: {
    // 设置加载状态
    SET_LOADING(state, loading) {
      state.loading = loading
    },
    // 设置错误信息
    SET_ERROR(state, error) {
      state.error = error
    },
    // 设置用户信息
    SET_USER(state, user) {
      state.user = user
    },
    // 设置认证状态
    SET_AUTHENTICATED(state, isAuthenticated) {
      state.isAuthenticated = isAuthenticated
    },
    // 设置token
    SET_TOKEN(state, token) {
      state.token = token
    },
    // 清除用户数据
    CLEAR_USER(state) {
      state.user = null
      state.token = null
      state.isAuthenticated = false
      state.error = null
    }
  },
  actions: {
    // 用户登录
    async login({ commit }, credentials) {
      commit('SET_LOADING', true)
      commit('SET_ERROR', null)
      
      try {
        const result = await currentAuthAPI.login(credentials)
        
        if (result.success) {
          const { user, token } = result.data
          commit('SET_USER', user)
          commit('SET_TOKEN', token)
          commit('SET_AUTHENTICATED', true)
          return { success: true }
        } else {
          commit('SET_ERROR', result.error)
          return { success: false, error: result.error }
        }
      } catch (error) {
        commit('SET_ERROR', error.message)
        return { success: false, error: error.message }
      } finally {
        commit('SET_LOADING', false)
      }
    },

    // 用户注册
    async register({ commit }, userData) {
      commit('SET_LOADING', true)
      commit('SET_ERROR', null)
      
      try {
        const result = await currentAuthAPI.register(userData)
        
        if (result.success) {
          return { success: true, data: result.data }
        } else {
          commit('SET_ERROR', result.error)
          return { success: false, error: result.error }
        }
      } catch (error) {
        commit('SET_ERROR', error.message)
        return { success: false, error: error.message }
      } finally {
        commit('SET_LOADING', false)
      }
    },

    // 用户登出
    async logout({ commit }) {
      commit('SET_LOADING', true)
      
      try {
        await currentAuthAPI.logout()
        commit('CLEAR_USER')
        localStorage.removeItem('authToken')
        localStorage.removeItem('userInfo')
        return { success: true }
      } catch (error) {
        // 即使登出失败，也要清除本地状态
        commit('CLEAR_USER')
        localStorage.removeItem('authToken')
        localStorage.removeItem('userInfo')
        return { success: true }
      } finally {
        commit('SET_LOADING', false)
      }
    },

    // 检查用户登录状态
    async checkAuth({ commit }) {
      const token = localStorage.getItem('authToken')
      const userInfo = localStorage.getItem('userInfo')
      
      if (token && userInfo) {
        try {
          commit('SET_TOKEN', token)
          commit('SET_USER', JSON.parse(userInfo))
          commit('SET_AUTHENTICATED', true)
          
          // 验证token是否仍然有效
          const result = await currentAuthAPI.getCurrentUser()
          if (result.success) {
            commit('SET_USER', result.data)
          } else {
            // token无效，清除状态
            commit('CLEAR_USER')
            localStorage.removeItem('authToken')
            localStorage.removeItem('userInfo')
          }
        } catch (error) {
          // token无效，清除状态
          commit('CLEAR_USER')
          localStorage.removeItem('authToken')
          localStorage.removeItem('userInfo')
        }
      }
    },

    // 清除错误信息
    clearError({ commit }) {
      commit('SET_ERROR', null)
    }
  },
  modules: {
  }
})
